import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '@/pages/HomePage.vue'
import UserLoginPage from '@/pages/user/UserLoginPage.vue'
import UserRegisterPage from '@/pages/user/UserRegisterPage.vue'
import { getToken } from '@/utils/auth.ts'
import AdminManagerPage from "@/pages/admin/AdminManagerPage.vue";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
    },
    {
      path: '/about',
      name: 'about',
      component: () => import('@/pages/AboutPage.vue'),
    },
    {
      path: '/admin/manager',
      name: 'adminManger',
      component: AdminManagerPage,
    },
    {
      path: '/user/login',
      name: 'userLogin',
      component: UserLoginPage,
    },
    {
      path: '/user/register',
      name: 'userRegister',
      component: UserRegisterPage,
    },
  ],
})

// 定义白名单
const whiteList = ['userLogin', 'userRegister', 'about'] // 允许未登录访问的页面

router.beforeEach((to, from, next) => {
  // 获取 token（从全局状态或本地存储中）
  if (!getToken()) {
    // 当 token 不存在时，禁止访问非登录页
    if (!whiteList.includes(<string>to.name)) {
      next({ name: 'userLogin' }) // 跳转到登录页面
    }
  }
  next() // 允许访问
})

export default router
